<template>
  <div>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input v-model="queryForm.roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="queryForm.roleKey" placeholder="权限字符"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryForm.status" placeholder="状态" clearable>
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="createTimeArray"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="batchDel">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="id"
          label="编号"
          width="55">
      </el-table-column>
      <el-table-column
          prop="roleName"
          label="角色名称"
          width="100">
      </el-table-column>
      <el-table-column
          prop="roleKey"
          label="权限字符"
          width="100">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          :formatter="statusFormatter"
          width="120">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              icon="el-icon-edit"
              round
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑
          </el-button>
          <el-button round
                     size="mini"
                     type="primary"
                     @click="handleMenu(scope.row)">分配菜单
          </el-button>
          <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)">删除
          </el-button>
        </template>

      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="current"
        :page-size="size"
        @current-change="changePage"
        :total="total">
    </el-pagination>

    <!-- 修改、添加角色弹框 -->
    <el-dialog title="角色" :visible.sync="roleFormVisible">
      <el-form :model="editUserForm">
        <el-form-item label="角色名">
          <el-input v-model="editUserForm.roleName" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="editUserForm.roleKey" placeholder="权限字符"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editUserForm.status" placeholder="状态" clearable>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole(editUserForm.oper)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配菜单弹框 -->
    <el-dialog title="用户角色" :visible.sync="roleMenuFormVisible" @close="resetRoleParam">
      <el-form>
        <el-form-item label="角色名">
          <el-tag type="success">{{currentRoleName}}</el-tag>
        </el-form-item>
        <span>权限</span>
          <el-tree
              :data="menuTree"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="menuTree"
              :default-checked-keys="checkedMenu"
              highlight-current
              :props="defaultProps">
          </el-tree>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleMenuFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Role from "../api/role";
import {Message} from "element-ui";



export default {
  data() {
    return {
      total: 0,
      size: 3,
      current: 1,
      deptList: [],
      tableData: [],
      queryForm: {},
      createTimeArray: ['', ''],
      multipleSelection: [],
      roleFormVisible: false,
      roleMenuFormVisible: false,
      editUserForm: {},
      imageUrl: '',
      checkedMenu: [],
      roleList: [],
      currentRoleName:'',
      currentRoleId:'',
      menuTree:[],
      defaultProps: {
        children: 'childrenMenu',
        label: 'label'
      }
    }
  },
  created() {
    this.onQuery();
  },
  methods: {
    getCheckedNodes() {
      console.log(this.$refs.menuTree.getCheckedNodes());
    },
    getCheckedKeys() {
      console.log(this.$refs.menuTree.getCheckedKeys());
    },
    changePage(page) {
      console.log('page==', page)
      this.current = page
      this.onQuery();
    },
    async onQuery() {
      this.queryForm.current = this.current
      if (this.createTimeArray && this.createTimeArray.length == 2) {
        this.queryForm.startDate = this.createTimeArray[0]
        this.queryForm.endDate = this.createTimeArray[1]
      } else {
        this.queryForm.startDate = ''
        this.queryForm.endDate = ''
      }
      this.queryForm.size = this.size
      let response = await Role.getRolePage(this.queryForm);
      this.tableData = response.records;
      this.total = response.total;
      this.size = response.size;
      this.current = response.current;
    },
    statusFormatter(row) {
      if (row.status == 0) {
        return "正常";
      } else if (row.status == 1) {
        return "停用";
      } else {
        return "-";
      }
    },
    //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection, 'this is selected')
    },
    //批量删除
    async batchDel() {
      if (this.multipleSelection) {
        var idList = []
        this.multipleSelection.forEach(o => {
          idList.push(o.id)
        })
      }
      if (idList.length == 0) {
        Message.error("请至少选择一条数据！")
        return;
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        await Role.deleteRole({"ids": idList});
        this.onQuery();
      }).catch(() =>{

      })
    },
    // 删除
    async handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await Role.deleteRole({"ids":id});
        this.onQuery();
      }).catch(() =>{

      })

    },
    // 点击编辑
    handleEdit(row) {
      this.roleFormVisible = true;
      // this.editUserForm = JSON.parse(JSON.stringify(this.row))  把复杂类型先转成字符串 字符串复制没有引用问题 然后再转过来
      this.editUserForm = {...row}; //es6解构赋值写法（把复杂类型的对象里的属性是简单类型的 一个个复制属性过去）如果对象里只有简单类型 没有复杂类型用解构赋值即可
      this.editUserForm.oper = 'update'
    },
    // 点击添加
    handleAdd() {
      this.roleFormVisible = true;
      // this.editUserForm = JSON.parse(JSON.stringify(this.row))  把复杂类型先转成字符串 字符串复制没有引用问题 然后再转过来
      this.editUserForm = {}; //es6解构赋值写法（把复杂类型的对象里的属性是简单类型的 一个个复制属性过去）如果对象里只有简单类型 没有复杂类型用解构赋值即可
      this.editUserForm.oper = 'add'
    },
    // 弹框关闭时清空参数
    resetRoleParam(){
      console.log('------resetRoleParam------')
      this.currentRoleId=''
      this.currentRoleName=''
      this.checkedMenu= []
      this.menuTree= []
    },
    // 点击分配菜单权限
    async handleMenu(row) {
      this.roleMenuFormVisible = true;
      this.currentRoleId=row.id
      this.currentRoleName=row.roleName
      console.log(row.id,'-----+++++++')
      let response = await Role.getMenuByRole({"roleId":row.id});
      this.menuTree = response.data;
      this.getCheckedMenu(this.menuTree)
      // console.log(this.checkedMenu)
    },
    getCheckedMenu(menuList){
      if (menuList.length == 0){
        return;
      }
      menuList.forEach(m =>{
        if (m.checked == 1){
          this.checkedMenu.push(m.id)
        }else {
          if (m.childrenMenu){
            this.getCheckedMenu(m.childrenMenu);
          }
        }
      })
    },


    async saveRole(oper) {
      if (oper == "update"){
        await Role.updateRole(this.editUserForm);
      }
      if (oper == "add"){
        await Role.addRole(this.editUserForm);
      }
      this.roleFormVisible = false
      this.editUserForm = {}
      this.onQuery()
    },
    async saveRoleMenu() {
      let checkedKeys = this.$refs.menuTree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
      let newChecked = checkedKeys.concat(halfCheckedKeys);
      console.log(newChecked);
      await Role.saveRoleMenu({"id":this.currentRoleId,"list":newChecked});
      this.roleMenuFormVisible = false
    }
  }
}
</script>

<style scoped>

</style>